package com.gitee.wsl.android.ui.crosstabdnd

import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.gitee.wsl.android.ui.crosstabdnd.DragAndDropUtil.getTabFragment
import java.util.Objects

class DraggedItemLocalState<TabFragment, ItemAdapter, ItemModel>(
    val draggedItemModel: ItemModel,
    /** The currently dragged view (can change when the tab changes  */
    var draggedView: View,
    var itemAdapter: ItemAdapter,
    var positionInItemAdapter: Int
) where TabFragment : Fragment, TabFragment : DragAndDropTab<ItemAdapter>, ItemAdapter : RecyclerView.Adapter<*>, ItemAdapter : DragAndDropAdapter<ItemModel> {

    /** The original dragged view  */
    val originalDraggedView: View = draggedView

    var insertedListener: RecyclerView.OnChildAttachStateChangeListener? = null
    lateinit var recyclerView: RecyclerView

    var currentTabId: Long = 0
        private set

    fun onDragStart(viewPager: ViewPager2, fm: FragmentManager) {
        currentTabId = Objects.requireNonNull(viewPager.adapter).getItemId(viewPager.currentItem)
        recyclerView = getTabFragment<TabFragment>(fm, currentTabId)!!.recyclerView
    }

    fun onTabChanged(viewPager: ViewPager2, fm: FragmentManager) {
        if (insertedListener != null) {
            recyclerView.removeOnChildAttachStateChangeListener(insertedListener!!)
            insertedListener = null
        }
        currentTabId = Objects.requireNonNull(viewPager.adapter).getItemId(viewPager.currentItem)
        recyclerView = getTabFragment<TabFragment>(fm, currentTabId)!!.recyclerView
        itemAdapter = recyclerView.adapter as ItemAdapter
    }
}